/**
 * All JS functions that deal with keyphrases and the keyphrases
 * grid
 *
 * @author Sean Hickey <sean@headzoo.com>
 * @version $Id: keyphrases.js 425 2008-07-09 16:27:54Z sean $
 */

dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dojox.grid.Grid");
dojo.require("dojox.grid._data.model");
dojo.require("dojo.parser");
dojo.require("dojo.dnd.Mover");
dojo.require("dojo.dnd.Moveable");
dojo.require("dojo.dnd.move");

var grid = new dojox.Grid({ "id": "grid"});
var store;
var movable_id;
var movable;
var form_id;
var cell_click_listener;

var view1_subrow = [
	{ name: '<input type="checkbox" id="select_all" title="Select all" onclick="gridSelectAll(this)" />',
	width: "30px", 
	styles: "text-align: center;",
	get: function (inRowIndex)
		{
			var isSel = grid.selection.isSelected(inRowIndex);
			var html = '<input type="checkbox"' + (isSel ? ' checked="checked"' : '') + "  />";
			return html;
		}
	},
	{ name: 'Phrase', width: "200px", field: 'phrase' }
];
 
var view1 = {
	noscroll: true,
	rows: [
		view1_subrow
	]
};
var view2_subrow = [
			{name: 'Description', width: "250px", field:'description'},
			{name: 'Created', width: "100px", field:'created', styles: "text-align: center;"},
			{name: 'Factory', width: "100px", field:'factory', styles: "text-align: center;"}
];
 
var view2 = {
	rows: [
		view2_subrow
	]
};

var layout = [ view1, view2 ];
	
function gridStartup()
{
	Alinks.call('Alinks_Keyphrase_Keeper.fetchAll',
		[true],
		function(response, ioArgs)
		{
			showKeyphrases(response);
			return response;
		},
		function(response, ioArgs)
		{
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	);
}

function showKeyphrases(response)
{
	store = new dojo.data.ItemFileReadStore({jsId: 'jsonStore', data: response});
	var ddata = new dojox.grid.data.DojoData(null, store, {jsId: 'model', clientSort: true, query: { hash: '*' }});
	
	grid.setModel(ddata);
	grid.setStructure(layout);
	grid.defaultHeight = "10em";
	
	dojo.byId("mygrid").appendChild(grid.domNode);
	grid.render();
	
	if (!cell_click_listener) {
		dojo.connect(grid, 'onSelected', function(inRowIndex)
			{
				grid.updateRow(inRowIndex);
			}
		);
		dojo.connect(grid, 'onDeselected', function(inRowIndex)
			{
				grid.updateRow(inRowIndex);
			}
		);
		dojo.connect(grid, 'onCellClick', function(evt)
			{
				var t = evt.target;
				if ( t.tagName.toLowerCase() == 'input' && t.type == 'checkbox') {
					var funcName = t.checked ? "addToSelection" : "deselect";
					grid.selection[funcName](evt.rowIndex);
				}
			}
		);
		cell_click_listener = dojo.connect(grid, 'onRowDblClick', function(evt)
			{
				editKeyphrase(grid.model.data[evt.rowIndex].hash);
			}
		);

		grid.selection.clickSelectEvent = function () { };
	}
}

function gridSelectAll(target)
{
	if (target.checked) {
		for(var i = 0; i < grid.model.data.length; i++) {
			grid.selection.setSelected(i, 1);
		}
	} else {
		grid.selection.clear();
	}
}

function keyphraseEditor(response)
{
	if (!response.success) {
		alinks_showAjaxNotice('aLinks Error', response.message, false);
		return;
	}
	eval("var response_form = " + response.form);
	var form = Alinks.Forms.jsonToForm(response_form);
	var table = document.createElement('DIV');
	movable_id = "movable" + Math.floor(Math.random() * 10000);
	table.id = movable_id;
	table.className = "alinks_keyphrases_floating_form";
	var handle = document.createElement('DIV');
	handle.className = 'alinks_keyphrases_floating_handle';
	handle.id = 'handle';
	handle.innerHTML = '<a href="javascript:closeKeyphraseEditor()">&nbsp;&nbsp;</a>';
	table.appendChild(handle);
	table.appendChild(form);
	
	document.body.appendChild(table);
	putInCenter(table);
	movable = new dojo.dnd.Moveable(movable_id, { handle: "handle"});
	console.log(movable);
}

function closeKeyphraseEditor()
{
	if (document.getElementById(movable_id)) {
		var editor = document.getElementById(movable_id);
		editor.style.display = 'none';
	}
}

function editKeyphrase(hash)
{
	Alinks.call('Alinks_Keyphrase_Keeper.editKeyphrasesForm',
		[hash],
		function(response, ioArgs)
		{
			keyphraseEditor(response);
			return response;
		},
		function(response, ioArgs)
		{
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	);	
}

function updateKeyphrase()
{
	var target = document.getElementById(form_id);
	for(var i = 0; i < target.elements.length; i++) {
		if (target.elements[i].getAttribute('alinksrequired') == '1' && !target.elements[i].value) {
			target.elements[i].parentNode.className = 'alinks_invalid';
			var message = document.createElement('UL');
			message.className = 'alinks_invalid_messages';
			var li = document.createElement('LI');
			li.innerHTML = target.elements[i].getAttribute('alinksrequiredmsg');
			message.appendChild(li);
			target.elements[i].parentNode.appendChild(message);
			return false;
		}
		if (target.elements[i].getAttribute('alinksmustmatch')) {
			var regexp = target.elements[i].getAttribute('alinksmustmatch');
			var re = new RegExp(regexp); 
			if (!re.test(target.elements[i].value)) {
				target.elements[i].parentNode.className = 'alinks_invalid';
				var message = document.createElement('UL');
				message.className = 'alinks_invalid_messages';
				var li = document.createElement('LI');
				li.innerHTML = target.elements[i].getAttribute('alinksmustmatchmsg');
				message.appendChild(li);
				target.elements[i].parentNode.appendChild(message);
				return false;
			}
		}
		if (target.elements[i].getAttribute('alinksnotmatch')) {
			var regexp = target.elements[i].getAttribute('alinksnotmatch');
			var re = new RegExp(regexp); 
			if (re.test(target.elements[i].value)) {
				target.elements[i].parentNode.className = 'alinks_invalid';
				var message = document.createElement('UL');
				message.className = 'alinks_invalid_messages';
				var li = document.createElement('LI');
				li.innerHTML = target.elements[i].getAttribute('alinksnotmatchmsg');
				message.appendChild(li);
				target.elements[i].parentNode.appendChild(message);
				return false;
			}
		}
	}
	
	var data = [];
	data["action"] = 'alinks_ajax_dispatch';
	data["method"] = 'Alinks_Keyphrase_Keeper.updateFromKeyphrasesForm';
	data["cookie"] = document.cookie;
	
	var deferred = dojo.xhrPost({
        url: wordpress_home + "/wp-admin/admin-ajax.php",
        handleAs: "json",
        timeout: 5000,
		content: data,
		form: target,
		load: function(response, ioArgs) {
			if (response.success == false || response.success == 'false') {
				alinks_showAjaxNotice('aLinks Error', response.message, true);
				return;
			}
			gridStartup();
			closeKeyphraseEditor();
			return response;
		},

		error: function(response, ioArgs) {
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	});

	return false;
}

function createKeyphrase()
{
	Alinks.call('Alinks_Factory_Keeper.getFactoryKeyphrasesForm',
		[document.getElementById('alinks_create_factory').value],
		function(response, ioArgs)
		{
			keyphraseEditor(response);
			return response;
		},
		function(response, ioArgs)
		{
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	);
}

function filterGrid()
{
	var filter = document.getElementById('filter').value;
	var filter_by = document.getElementById('filter_by').value;
	filter += '*';
	eval('var filter_query = {' + filter_by + ': "' + filter + '"}');
	var newModel = new dojox.grid.data.DojoData(null, null, {rowsPerPage: 20, store: store, queryOptions: {ignoreCase: true}, query: filter_query, clientSort: true});
	grid.setModel(newModel);
}

function handleKeyPress(e, form, func)
{
	var key=e.keyCode || e.which;
	if (key == 13) {
		func();
	}
}

function deleteKeyphrases()
{
	if (grid.selection.getSelected().length == 0) {
		alert("You haven't selected any keyphrases");
		return;
	}
	var answser;
	var selected = grid.selection.getSelected();
	if (selected.length == 1) {
		var keyphrase = grid.model.data[selected[0]];
		answer = confirm("Are you sure you want to delete the keyphrase '" + keyphrase.phrase + "'?");
	} else {
		answer = confirm("Are you sure you want to delete " + selected.length + " keyphrases?");
	}
	if (!answer) {
		return;
	}
	
	var args = new Array();
	for(var i = 0; i < selected.length; i++) {
		args[i] = grid.model.data[selected[i]].hash;
	}
	
	Alinks.call('Alinks_Keyphrase_Keeper.deleteByHashes',
		[args],
		function(response, ioArgs)
		{
			confirmAction(response);
			gridStartup();
			grid.selection.clear();
			return response;
		},
		function(response, ioArgs)
		{
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	);
}

function exportKeyphrases()
{
	if (grid.selection.getSelected().length == 0) {
		alert("You haven't selected any keyphrases");
		return;
	}
	var selected = grid.selection.getSelected();
	var args = [];
	for(var i = 0; i < selected.length; i++) {
		args[i] = grid.model.data[selected[i]].hash;
	}
	
	Alinks.call('Alinks_ImportExport_Export_Ajax.exportKeyphrases',
		[args],
		function(response, ioArgs)
		{
			finishExport(response);
			return response;
		},
		function(response, ioArgs)
		{
			console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	);
}

function finishExport(response)
{
	if (response.success) {
		window.location = response.file_url + "&cookie=" + document.cookie;
	}
}

function confirmAction(response)
{
	var title;
	if (!response.success) {
		title = 'aLinks Error';
	} else {
		title = 'aLinks Success';
	}
	alinks_showAjaxNotice(title, response.message, !response.success);
}

function putInCenter(element)
{
	var d = document;
	var rootElm = (document.documentElement && document.compatMode == 'CSS1Compat') ? document.documentElement : document.body;
	var vpw = self.innerWidth ? self.innerWidth : rootElm.clientWidth; // viewport width
	var vph = self.innerHeight ? self.innerHeight : rootElm.clientHeight; // viewport height
	element.style.position = 'absolute';
	element.style.left = ((vpw - element.offsetWidth) / 2) + 'px';
	element.style.top = (rootElm.scrollTop + (vph - element.offsetHeight) / 2 ) + 'px';
}

dojo.addOnLoad(gridStartup);